package com.itserver.controller.common;


import com.itserver.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Slf4j
@RestController
public class UploadController {
    @Value("${file.upload-dir}")
    private String uploadDir;

    @Value("${file.base-url}")
    private String baseUrl;

    @PostMapping("/file/uploadFile")
    public Result upload(String name, Integer age, MultipartFile file) throws IOException {
        log.info("文件上传:{}",file);
        String orginalFilename = file.getOriginalFilename();
//        新文件名
        String extension = null;
        if (orginalFilename != null) {
            extension = orginalFilename.substring(orginalFilename.lastIndexOf("."));
        }
        String newFilename = UUID.randomUUID() + extension;

        Path path = Paths.get(uploadDir);
        if (!Files.exists(path)) {
            Files.createDirectories(path);
        }
        String pathname = uploadDir + newFilename;
        file.transferTo(new File(pathname));
        log.info("文件上传成功:{}",pathname);
        Object data =  baseUrl+newFilename;
        return Result.success(data);
    }
}
